document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('inference-form');
    const resultDiv = document.getElementById('result');

    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        try {
            // 获取输入数据
            const inputData = document.getElementById('input-data').value;
            const data = {
                input: JSON.parse(inputData)
            };

            // 发送推理请求
            const response = await fetch('/inference/inference', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.status === 'success') {
                // 显示结果
                resultDiv.innerHTML = `
                    <div class="alert alert-success">
                        <h6>诊断结果</h6>
                        <p>预测类别: ${result.prediction}</p>
                        <p>置信度: ${(result.confidence * 100).toFixed(2)}%</p>
                    </div>
                `;

                // 绘制置信度分布图
                const trace = {
                    x: Array.from({length: result.probabilities.length}, (_, i) => `类别 ${i}`),
                    y: result.probabilities.map(p => p * 100),
                    type: 'bar',
                    marker: {
                        color: result.probabilities.map((_, i) => 
                            i === result.prediction ? '#28a745' : '#007bff'
                        )
                    }
                };

                const layout = {
                    title: '各类别置信度分布',
                    xaxis: {title: '故障类别'},
                    yaxis: {title: '置信度 (%)', range: [0, 100]}
                };

                Plotly.newPlot('confidence-plot', [trace], layout);
            } else {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <p>错误: ${result.message}</p>
                    </div>
                `;
            }
        } catch (error) {
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <p>发生错误: ${error.message}</p>
                </div>
            `;
        }
    });
}); 